<?php

function custom_template_echo_slice_activities_shared(& $args) {
	global $app_list_strings, $app_strings;
	
	global $shared_user, $timedate;


	$schedule_note_image = SugarThemeRegistry::current()->getImageURL('schedule_note.gif');

	require_once('modules/edanz_Editor/metadata/additionalDetails.php');
//		$ad_function = 'additionalDetails' . $act->sugar_bean->object_name;
//		$results = $ad_function($fields);
	$results = scheduleNoteDetails($shared_user->id, $args['slice']->start_time);
	$results['string'] = str_replace(array("&#039", "'"), '\&#039', $results['string']);

	if(!empty($results['string'])){
		$extra = "onmouseover=\"return overlib('" . 
					str_replace(array("\rn", "\r", "\n"), array('','','<br />'), $results['string'])
					. "', CAPTION, '{$app_strings['LBL_SCHEDULE_NOTES']}"
					. "', DELAY, 200, STICKY, MOUSEOFF, 1000, WIDTH, " 
					.(empty($results['width']) ? '330' : $results['width']) 
					. ", CLOSETEXT, '<img border=0  style=\'margin-left:2px; margin-right: 2px;\' src=".SugarThemeRegistry::current()->getImageURL('close.gif').">', "
					. "CLOSETITLE, '{$app_strings['LBL_ADDITIONAL_DETAILS_CLOSE_TITLE']}', CLOSECLICK, FGCLASS, 'olFgClass', "
					. "CGCLASS, 'olCgClass', BGCLASS, 'olBgClass', TEXTFONTCLASS, 'olFontClass', CAPTIONFONTCLASS, 'olCapFontClass', CLOSEFONTCLASS, 'olCloseFontClass');\" "
					. "onmouseout=\"return nd(1000);\" ";

		echo "<span $extra><img vertical-align='middle' class='info' border='0' src='$schedule_note_image'></span>";
	}

	// Signal Unavailability
	if($results['unavailable']){
		echo "<img border=0  style=\'margin-left:2px; margin-right: 2px;\' src=".SugarThemeRegistry::current()->getImageURL('unavailable.gif').">";
	}

	// Start of Task breakdown
	if(empty($args['slice']->acts_arr[$shared_user->id])) {
		return;
	}
	$task_count = 0;
	$work_load = Array();
	$workload_breakdown = Array();
	$origin_systems = Array();

	foreach($args['slice']->acts_arr[$shared_user->id] as $act) {
		if($act->sugar_bean->object_name == 'Task') {
			if(!empty($act->sugar_bean->type) && !empty($act->sugar_bean->workload)){
				$task_count++;
				if($act->sugar_bean->status != 'Deferred'){
					if (!array_key_exists($act->sugar_bean->type, $work_load)){
						$work_load[$act->sugar_bean->type] = Array();
					}
					array_push($work_load[$act->sugar_bean->type], $act->sugar_bean->workload);
				}
				if (!in_array($act->sugar_bean->origin_system, $origin_systems)){
					array_push($origin_systems, $act->sugar_bean->origin_system);
				}
				$task = array("type" => $act->sugar_bean->type, "origin_system" => $act->sugar_bean->origin_system, "origin_module" => $act->sugar_bean->origin_module, "origin_id" => $act->sugar_bean->origin_id, "workload" => $act->sugar_bean->workload, "status" => $act->sugar_bean->status, "name" => $act->sugar_bean->name, "id" => $act->sugar_bean->id);
	                        array_push($workload_breakdown, $task);

			}
		}
	}
	if($task_count > 0){
		$breakdown_element_id = $shared_user->id.$args['slice']->end_time->ts;

		echo "<div style=\"margin-top: 1px;\">
		<a href=\"javascript: toggleDisplay('".$breakdown_element_id."');\" title=\"".$app_strings['LBL_TOGGLE_BREAKDOWN']."\"><table cellpadding=\"1\" cellspacing=\"0\" border=\"0\" width=\"100%\" class=\"olBgClass\"><tbody>";
		foreach($work_load as $key=>$val){
			echo "<tr>";
			echo "<td>".$app_list_strings['task_type_dom'][$key]."</td>";
			echo "<td>".array_sum($val).' '.$app_list_strings['task_type_units'][$key]."</td>";
			echo "</tr>";
		}
		$deferred_tasks = array_filter($workload_breakdown, function ($element) use ($origin) { return ($element['status'] == 'Deferred'); } );
		if(count($deferred_tasks)){
			echo"<tr>";
                        echo "<td colspan=\"2\">".count($deferred_tasks)." Reassigned"."</td>";
			echo "</tr>";
		}
		echo "</tbody></table></a>";
		echo "<div id=\"".$breakdown_element_id."\" style=\"display:none\">";
		foreach($origin_systems as $origin){
			$origin_filtered_tasks = array_filter($workload_breakdown, function ($element) use ($origin) { return ($element['origin_system'] == $origin); } );
			usort($origin_filtered_tasks, function ($func_a, $func_b) {return strcmp($func_a['name'], $func_b['name']);});
			echo "<table class=\"yui-calendar\" width=\"100%\" cellspacing=\"0\" cellpadding=\"2\" border=\"0\"><tbody>";
			echo "<tr><th colspan=4><strong>".$app_list_strings['origin_systems'][$origin]."</strong></th></tr>";
			foreach($origin_filtered_tasks as $task){
				echo "<tr>";
				echo "<td><a href=\"".$task['origin_system']."/index.php?action=DetailView&module=".$task['origin_module']."&record=".$task['origin_id']."\" target=\"_blank\">".$task['name']."</a></td>";
				echo "<td>".$task['workload'].' '.$app_list_strings['task_type_units'][$task['type']]."</td>";
				echo "<td>".$app_list_strings['task_type_dom'][$task['type']]."</td>";
				echo "<td";
				switch ($task['status']){
					case 'Deferred':
						echo " class=\"calcell highlight3\"";
						break;
					case 'Completed':
						echo " class=\"calcell highlight4\"";
                                                break;
				}
				echo ">".$app_list_strings['task_status_dom'][$task['status']]."</td>";
				echo "</tr>";

			}
		echo "</tbody></table>";
		}
		echo "</div>";
	}
}


function editor_name_heading(){
	global $shared_user, $app_strings;
	echo '<h5 class="calSharedUser">'.$shared_user->full_name;
        $jsinfoImage = SugarThemeRegistry::current()->getImageURL('info_inline.gif');
	require_once('modules/edanz_Editor/metadata/additionalDetails.php');

	$results = scheduleNoteDetails($shared_user->id);
	$results['string'] = str_replace(array("&#039", "'"), '\&#039', $results['string']);

	if(!empty($results['string'])){
		$extra = "onmouseover=\"return overlib('" . 
					str_replace(array("\rn", "\r", "\n"), array('','','<br />'), $results['string'])
					. "', CAPTION, '{$app_strings['LBL_SCHEDULE_NOTES']}"
					. "', DELAY, 200, STICKY, MOUSEOFF, 1000, WIDTH, " 
					.(empty($results['width']) ? '310' : $results['width']) 
					. ", CLOSETEXT, '<img border=0  style=\'margin-left:2px; margin-right: 2px;\' src=".SugarThemeRegistry::current()->getImageURL('close.gif').">', "
					. "CLOSETITLE, '{$app_strings['LBL_ADDITIONAL_DETAILS_CLOSE_TITLE']}', CLOSECLICK, FGCLASS, 'olFgClass', "
					. "CGCLASS, 'olCgClass', BGCLASS, 'olBgClass', TEXTFONTCLASS, 'olFontClass', CAPTIONFONTCLASS, 'olCapFontClass', CLOSEFONTCLASS, 'olCloseFontClass');\" "
					. "onmouseout=\"return nd(1000);\" ";

		echo "<span $extra><img vertical-align='middle' class='info' border='0' src='$jsinfoImage'></span>";
	}
/*
	echo "<span id='adspan_" . $editor->id . "' onmouseout=\"return SUGAR.util.clearAdditionalDetailsCall()\" " 
                . "onmouseover=\"lvg_dtails('$editor->id')\" "
				. "onmouseout=\"return nd(1000);\" style='position: relative;'><img vertical-align='middle' class='info' border='0' src='$jsinfoImage'></span>";
*/
	if($shared_user->isNewEditor()){
		echo '<span style="font-style:italic">'.$app_strings['LBL_NEW_EDITOR'].'</span>';
	}
	echo '</h5>';
}

function set_chooser_js(){
$the_script  = <<<EOQ

<script type="text/javascript" language="Javascript">
<!--  to hide script contents from old browsers

function set_chooser()
{



var shared_ids_def = '';

var display_td = document.getElementById('shared_ids_td');

var display_ref = display_td.getElementsByTagName('select')[0];

for(i=0; i < display_ref.options.length ;i++)
{
//         shared_ids_def += "shared_ids[]="+display_ref.options[i].value+"&";
	display_ref.options[i].selected = "1";
}

//document.shared_cal.shared_ids_def.value = shared_ids_def;

}
// end hiding contents from old browsers  -->
</script>
EOQ;

return $the_script;

}

function editor_historic_rates($average_punctuality){
	global $shared_user, $app_strings, $app_list_strings, $db;
/*
	$query = "SELECT type,
			SUM(IF(EXTRACT(YEAR_MONTH FROM CURDATE()) = EXTRACT(YEAR_MONTH FROM IFNULL(completed_date, date_due)), workload, 0)) AS ThisMonthworkload,
			SUM(workload) as TotalWorkload,
			PERIOD_DIFF(EXTRACT(YEAR_MONTH FROM CURDATE()), EXTRACT(YEAR_MONTH FROM MIN(IFNULL(completed_date, date_due)))) AS MonthsSinceFirstTask,
			SUM(workload)/ PERIOD_DIFF(EXTRACT(YEAR_MONTH FROM CURDATE()), EXTRACT(YEAR_MONTH FROM MIN(IFNULL(completed_date, date_due)))) AS AverageMonthlyLoad,
			COUNT(*)+IFNULL(historic_task_totals.task_count, 0) as TotalTasks
		FROM tasks
		LEFT JOIN historic_task_totals 
			ON tasks.assigned_user_id = user_id 
			AND tasks.type = task_type
		WHERE workload IS NOT NULL
			AND status <> 'Deferred'
			AND status <> 'Pending Input'
			AND assigned_user_id = '".$shared_user->id."'
			AND deleted = 0
		GROUP BY type

		UNION

		SELECT task_type AS type,
			SUM(IF(EXTRACT(YEAR_MONTH FROM CURDATE()) = EXTRACT(YEAR_MONTH FROM IFNULL(completed_date, date_due)), workload, 0)) AS ThisMonthworkload,
			SUM(workload) as TotalWorkload,
			PERIOD_DIFF(EXTRACT(YEAR_MONTH FROM CURDATE()), EXTRACT(YEAR_MONTH FROM MIN(IFNULL(completed_date, date_due)))) AS MonthsSinceFirstTask,
			SUM(workload)/ PERIOD_DIFF(EXTRACT(YEAR_MONTH FROM CURDATE()), EXTRACT(YEAR_MONTH FROM MIN(IFNULL(completed_date, date_due)))) AS AverageMonthlyLoad,
			SUM(IF(id IS NOT NULL, 1, 0))+IFNULL(historic_task_totals.task_count, 0) as TotalTasks
		FROM historic_task_totals 
		LEFT JOIN tasks 
			ON tasks.assigned_user_id = user_id 
			AND tasks.type = task_type 
			AND workload IS NOT NULL
			AND status <> 'Deferred'
			AND status <> 'Pending Input'
			AND deleted = 0
		WHERE user_id = '".$shared_user->id."'
		GROUP BY type";
*/
	$query = "SELECT type, MAX(ThisMonthworkload) AS ThisMonthworkload, MAX(TotalWorkload) AS TotalWorkload, MAX(MonthsSinceFirstTask) AS MonthsSinceFirstTask, MAX(AverageMonthlyLoad) AS AverageMonthlyLoad, SUM(Tasks) AS TotalTasks
		FROM(

			SELECT type,
						SUM(IF(EXTRACT(YEAR_MONTH FROM CURDATE()) = EXTRACT(YEAR_MONTH FROM IFNULL(completed_date, date_due)), workload, 0)) AS ThisMonthworkload,
						SUM(workload) as TotalWorkload,
						PERIOD_DIFF(EXTRACT(YEAR_MONTH FROM CURDATE()), EXTRACT(YEAR_MONTH FROM MIN(IFNULL(completed_date, date_due)))) AS MonthsSinceFirstTask,
						SUM(workload)/ PERIOD_DIFF(EXTRACT(YEAR_MONTH FROM CURDATE()), EXTRACT(YEAR_MONTH FROM MIN(IFNULL(completed_date, date_due)))) AS AverageMonthlyLoad,
						COUNT(*) as Tasks
			FROM tasks

			WHERE workload IS NOT NULL
				AND status <> 'Deferred'
				AND status <> 'Pending Input'
				AND assigned_user_id = '".$shared_user->id."'
				AND deleted = 0
			GROUP BY type

			UNION

			SELECT task_type AS type,
				0 AS ThisMonthworkload,
				0 as TotalWorkload,
				NULL AS MonthsSinceFirstTask,
				NULL AS AverageMonthlyLoad,
				IFNULL(historic_task_totals.task_count, 0) as TotalTasks
			FROM historic_task_totals
			
			WHERE user_id = '".$shared_user->id."'
			GROUP BY type
		) AS CombinedTotals
		GROUP BY type";

	$result = $db->query($query);
	
        echo "<table ><tr><th></th><th>";
        echo $app_strings['LBL_THIS_MONTH_LOAD'];
        echo "</th><th>";
        echo $app_strings['LBL_MEAN_MONTH_LOAD'];
        echo "</th><th>";
        echo $app_strings['LBL_TOTAL_TASKS'];
        echo "</th></tr>";
	
	while ($row = $db->fetchByAssoc($result)) {
		echo "<tr><td>";
		echo $app_list_strings['task_type_dom'][$row['type']];
		echo "</td><td>";
		echo $row['ThisMonthworkload'].' '.$app_list_strings['task_type_units'][$row['type']];
		echo "</td><td>";
		echo (empty($row['AverageMonthlyLoad'])?'N/A':round($row['AverageMonthlyLoad']).' '.$app_list_strings['task_type_units'][$row['type']]);
		echo "</td><td>";
		echo $row['TotalTasks'];
		echo "</td></tr>";
	}
	echo "</table>";

	echo "<table border=1 width=\"100%\"><tr><th></th><th>";
	echo $app_strings['LBL_PERSONAL'];
	echo "</th><th>";
        echo $app_strings['LBL_ALL_EDITORS'];
        echo "</th></tr><tr><td>";
	echo $app_strings['LBL_PUNCTUALITY'];
	echo "</td><td>";
	echo $shared_user->completion_punctuality;
	echo "</td><td>";
        echo $average_punctuality;
	echo "</td></tr></table>";
}

function get_punctuality($editor_id = NULL){
	global $db;
	$query = "SELECT
                        SUM(IF(TIMEDIFF(`completed_date`, `date_due`) < '00:30:00', 1, 0)) as on_time,
                        COUNT(*) as total
                FROM tasks
                WHERE status= 'Completed'
			AND deleted = 0
			AND date_due IS NOT NULL";
	if(!empty($editor_id)){
		$query .= "  AND assigned_user_id = '".$editor_id."'";
	}

	$result = $db->query($query,true," Error getting average punctuality: ");

	$row = $db->fetchByAssoc($result);

	if($row != null && $row['total'] > 0)
	{
		return round(100*$row['on_time']/$row['total']).'%';
	}
	else
	{
		return 'N/A';
	}
}
?>
